package br.com.iswe.gwt.ui.client.service;

import java.util.List;

import br.com.iswe.core.entidades.gwt.RemoteEntityObject;
import br.com.iswe.gwt.ui.client.ClientInfoContext;
import br.com.iswe.gwt.ui.client.CommonConstants;
import br.com.iswe.gwt.ui.client.QueryInfo;
import br.com.iswe.gwt.ui.client.RequestInfo;

import com.google.gwt.core.client.GWT;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;

@SuppressWarnings("unchecked")
public class CrudServiceClientImpl<E extends RemoteEntityObject> extends ServiceClientAbstract {
	
	protected static final CommonConstants commonConstants = (CommonConstants) GWT.create(CommonConstants.class);
	/**
	 * ManterServiceAsync : Servico Manter
	 */
	protected CrudServiceAsync<E> serviceAsync;
	
	public CrudServiceClientImpl(String controllerName) {
		super(controllerName);
		this.serviceAsync = (CrudServiceAsync)GWT.create(CrudService.class); 
		((ServiceDefTarget)serviceAsync).setServiceEntryPoint(GWT.getModuleBaseURL() + "crudServiceImpl");
	}
	
	public CrudServiceAsync<E> getServiceAsync() {
		return serviceAsync;
	}
	
	public ManyToManyClientAsyncContract getManyToManyClientAsyncContract(){
		return serviceAsync;
	}

	public void save(E entity, AsyncCallback<E> callback){
		save(entity, callback, null);
	}
	public void save(E entity, AsyncCallback<E> callback, RequestInfo requestInfo){
		if(requestInfo == null){
			requestInfo = new RequestInfo();
		}
		requestInfo.setup(ClientInfoContext.getClientInfoContext().getSessionInfo());
		
		serviceAsync.save(this.controllerName, 
				entity,
				requestInfo, 
				getCallBack(callback));
	}

	public void getAllObjects(QueryInfo queryInfo, AsyncCallback<List<E>> asyncCallback) {
		serviceAsync.getAllObjects(this.controllerName, queryInfo, (AsyncCallback<List<E>>)getCallBack(asyncCallback));
	}
	
	public void getObjects(E entity, QueryInfo queryInfo, AsyncCallback<List<E>> asyncCallback) {
		serviceAsync.getObjects(this.controllerName, entity, queryInfo, (AsyncCallback<List<E>>)getCallBack(asyncCallback));
	}

	public void detail(E entity, QueryInfo queryInfo, AsyncCallback<E> asyncCallback) {
		serviceAsync.detail(this.controllerName, entity, queryInfo, (AsyncCallback<E>)getCallBack(asyncCallback));
	}
	
	public void delete(E entity, AsyncCallback<Boolean> asyncCallback) {
		RequestInfo requestInfo = new RequestInfo();
		requestInfo.setup(ClientInfoContext.getClientInfoContext().getSessionInfo());
		serviceAsync.delete(this.controllerName, entity, requestInfo, getCallBack(asyncCallback));
	}
	
	public void deleteAll(List<E> entities, AsyncCallback<Boolean> asyncCallback) {
		RequestInfo requestInfo = new RequestInfo();
		requestInfo.setup(ClientInfoContext.getClientInfoContext().getSessionInfo());
		serviceAsync.deleteAll(this.controllerName, entities, requestInfo, getCallBack(asyncCallback));
	}
	
}
